package utils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import ui.AgCodeMain;

import java.awt.*;
import java.io.*;
import java.util.Map;

/**
 * Created by liushun on 2016/11/24.
 */
public class FreemarkerUtil {

    public static void write(Map obj, String ftl, String filePath, String desc) throws Exception {
        BufferedWriter out = null;
        try {
            Configuration cfg = new Configuration();
            cfg.setDefaultEncoding("utf-8");
            cfg.setDirectoryForTemplateLoading(new File(filePath));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            Template temp = cfg.getTemplate(ftl);
            File f = new File(desc);
            if (!f.getParentFile().exists())
                f.getParentFile().mkdirs();
            // FileOutputStream writerStream = new FileOutputStream(desc);
            // out = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
            out = new BufferedWriter(new FileWriter(desc, false));
            temp.process(obj, out);
            out.flush();
            out.close();
            AgCodeMain.log(obj.get("class") + ".java 生成完成!", Color.blue, true);
        }catch (Exception e){
            e.printStackTrace();
            out.flush();
            out.close();
            AgCodeMain.log("配置文件有误, 请检查!", Color.red, true);
        }
    }
}
